package com.zx.idc.backend.gui.sys.login;


import com.zx.idc.backend.gui.shiro.IncorrectCaptchaException;
import com.zx.idc.cache.sys.CaptchaCacheService;
import com.zx.idc.common.exception.GlobalException;
import com.zx.idc.common.spring.SpringBeanUtil;
import com.zx.idc.common.spring.SpringConfigUtil;
import com.zx.idc.ds.sys.service.ISysConfigurationService;
import org.apache.commons.codec.CharEncoding;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.DecimalFormat;
import java.util.Objects;

/**
 * @author rxliuli
 */
@Service
public class MailClient {

    private final Logger log = LoggerFactory.getLogger(MailClient.class);
    private JavaMailSender javaMailSender = SpringBeanUtil.getBean(JavaMailSender.class);
    private MailContentBuilder mailContentBuilder = SpringBeanUtil.getBean(MailContentBuilder.class);

    @Autowired
    private CaptchaCacheService cache;

    @Autowired
    private ISysConfigurationService sysConfigurationService;

    /**
     * 发送验证码邮件
     *
     * @param to 收件人邮箱
     */
    public void sendCode(String to) {
        if (StringUtils.isNotEmpty(cache.get(to))) {
            throw new GlobalException("已发送验证码，请不要重复发送！");
        }
        final String code = new DecimalFormat("0000").format(RandomUtils.nextInt(1, 10000));
        log.info(code);
        final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            final MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, CharEncoding.UTF_8);
            final String from = SpringConfigUtil.get("spring.mail.username");
            if (StringUtils.isEmpty(from)) {
                throw new GlobalException("发件人不能为空");
            }
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject("登录验证码");
            helper.setText(mailContentBuilder.buildVerificationCodeTemplate(code), true);
        } catch (MessagingException e) {
            log.error("发送验证码失败", e);
            throw new GlobalException("发送登录验证码失败");
        }
        javaMailSender.send(mimeMessage);
        cache.set(to, code);
    }

    /**
     * 校验验证码是否存在
     *
     * @param regMail 注册邮箱
     * @param code    验证码
     * @return 验证码是否存在
     */
    public void verifyCode(String regMail, String code) {
        final String cacheCode = cache.get(regMail);
        if (StringUtils.isEmpty(cacheCode)) {
            throw new IncorrectCaptchaException("验证码已失效！");
        }
        if (!Objects.equals(cacheCode, code)) {
            throw new IncorrectCaptchaException("验证码不正确！");
        }
        cache.set(regMail, "");
    }

    /**
     * 测试邮件功能
     *
     * @param to 接收邮箱
     * @return 是否成功
     */
    public Boolean sendTestEmail(String to) {
        try {
            return sendEmail(to, "主题: 简单邮件", "测试邮件内容");
        } catch (Exception e) {
            log.error("send test email is fail", e);
            return false;
        }
    }

    public void sendAlarmEmail(String subject, String text) {
        String to = sysConfigurationService.getVal("alarmSetting_mail_cus");
        if (StringUtils.isEmpty(to)) {
            log.error("没有设置客户报警邮箱");
        }
        try {
            sendEmail(to, subject, text);
        } catch (Exception e) {
            log.error("send alarm email is fail", e);
        }
    }

    /**
     * 指定接收邮箱发送邮件
     *
     * @param to      接收邮箱
     * @param subject 邮件主题
     * @param text    邮件内容
     * @return 发送成功
     */
    private Boolean sendEmail(String to, String subject, String text) {
        JavaMailSenderImpl javaMailSender = SpringBeanUtil.getBean(JavaMailSenderImpl.class);
        String alarmSetting_mail_host = sysConfigurationService.getVal("alarmSetting_mail_host");
        if (StringUtils.isNotEmpty(alarmSetting_mail_host)) {
            javaMailSender.setHost(alarmSetting_mail_host);
        }
        String alarmSetting_mail_port = sysConfigurationService.getVal("alarmSetting_mail_port");
        if (StringUtils.isNotEmpty(alarmSetting_mail_port)) {
            javaMailSender.setPort(Integer.parseInt(alarmSetting_mail_port));
        }
        String alarmSetting_mail_user = sysConfigurationService.getVal("alarmSetting_mail_user");
        if (StringUtils.isNotEmpty(alarmSetting_mail_user)) {
            javaMailSender.setUsername(alarmSetting_mail_user);
        }
        String alarmSetting_mail_pass = sysConfigurationService.getVal("alarmSetting_mail_pass");
        if (StringUtils.isNotEmpty(alarmSetting_mail_pass)) {
            javaMailSender.setPassword(alarmSetting_mail_pass);
        }
        String alarmSetting_mail_charset = sysConfigurationService.getVal("alarmSetting_mail_charset");
        if (StringUtils.isNotEmpty(alarmSetting_mail_charset)) {
            javaMailSender.setDefaultEncoding(alarmSetting_mail_charset);
        }
        String alarmSetting_mail_ssl = sysConfigurationService.getVal("alarmSetting_mail_ssl");
        if (alarmSetting_mail_ssl.equals("1")) {
            javaMailSender.getJavaMailProperties().setProperty("mail.smtp.socketFactory.port", "465");//设置ssl端口
            javaMailSender.getJavaMailProperties().setProperty("mail.smtp.socketFactory.fallback", "false");
            javaMailSender.getJavaMailProperties().setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }
        final SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(StringUtils.isNotEmpty(javaMailSender.getUsername()) ? javaMailSender.getUsername() : "");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        javaMailSender.send(message);
        return true;
    }


}
